package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.mapper.DailyPracticesMapper;
import com.scuec.groupfive.service.DailyPracticesService;
import com.scuec.groupfive.vo.DailyPracticesVO;
import com.scuec.groupfive.vo.AnswerResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DailyPracticesServiceImpl implements DailyPracticesService {

    @Autowired
    private DailyPracticesMapper dailyPracticesMapper;

    @Override
    public List<DailyPracticesVO> getDailyPracticesByUserId(Long userId) {
        return dailyPracticesMapper.getDailyPracticesByUserId(userId);
    }

    @Override
    @Transactional
    public List<AnswerResultVO> submitAnswers(Long userId, List<Map<String, Object>> answers) {
        List<AnswerResultVO> resultList = new ArrayList<>();
        List<Long> questionIds = new ArrayList<>();

        for (Map<String, Object> answer : answers) {
            questionIds.add(Long.valueOf(answer.get("questionId").toString()));
        }

        // 获取题目正确答案和解析
        List<AnswerResultVO> correctAnswers = dailyPracticesMapper.getCorrectAnswers(
                questionIds.toArray(new Long[0])
        );
        // 计算总用时（秒）
        int totalSeconds = answers.stream()
                .mapToInt(answer -> Integer.parseInt(answer.get("timeSpent").toString()))
                .sum();
        for (Map<String, Object> answer : answers) {
            Long questionId = Long.valueOf(answer.get("questionId").toString());
            String userAnswer = answer.get("answer").toString();
            Integer timeSpent = Integer.valueOf(answer.get("timeSpent").toString());
            String choices = (String) answer.get("choices");

            AnswerResultVO correctAnswer = null;
            for (AnswerResultVO ca : correctAnswers) {
                if (ca.getQuestionId().equals(questionId)) {
                    correctAnswer = ca;
                    break;
                }
            }

            if (correctAnswer != null) {
                AnswerResultVO result = new AnswerResultVO();
                result.setQuestionId(questionId);
                result.setSubject(correctAnswer.getSubject());
                result.setExamType(correctAnswer.getExamType());
                result.setQuestionContent(correctAnswer.getQuestionContent());
                result.setQuestionType(correctAnswer.getQuestionType());
                result.setUserAnswer(userAnswer);
                result.setCorrectAnswer(correctAnswer.getCorrectAnswer());
                result.setAnalysis(correctAnswer.getAnalysis());
                result.setTimeSpent(timeSpent);
                result.setChoices(choices);

                if ("single_choice".equals(correctAnswer.getQuestionType())) {
                    result.setIsCorrect(userAnswer.equalsIgnoreCase(correctAnswer.getCorrectAnswer()));
                } else if ("fill_in_the_blank".equals(correctAnswer.getQuestionType())) {
                    result.setIsCorrect(userAnswer.trim().equalsIgnoreCase(correctAnswer.getCorrectAnswer().trim()));
                } else {
                    result.setIsCorrect(null);
                }

                resultList.add(result);

                dailyPracticesMapper.insertAnswerRecord(
                        userId,
                        questionId,
                        correctAnswer.getQuestionType(),
                        userAnswer,
                        result.getIsCorrect(),
                        totalSeconds,  // 使用总用时而不是单题用时
                        correctAnswer.getSubject()
                );
                if (result.getIsCorrect() != null && !result.getIsCorrect()) {
                    dailyPracticesMapper.insertWrongQuestion(
                            userId,
                            questionId,
                            correctAnswer.getSubject()
                    );
                }
            }
        }

        dailyPracticesMapper.updateTaskStatus(userId);
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getDailyPracticeRecords(Long userId, String startDate,
                                                             String endDate, String keyword,
                                                             int page, int size) {
        return dailyPracticesMapper.getDailyPracticeRecords(
                userId, startDate, endDate, keyword, page, size);
    }

    @Override
    public List<AnswerResultVO> getPracticeResults(Long userId, String practiceId) {
        // 从 practiceId 中提取日期
        String practiceDate = practiceId.replace("daily_", "");
        return dailyPracticesMapper.getPracticeResults(userId, practiceDate);
    }

    @Override
    @Transactional
    public boolean updateFavoriteStatus(Long recordId, int isFavorite, Long userId, Long questionId) {
        // 更新答题记录的收藏状态
        int updated = dailyPracticesMapper.updateFavoriteStatus(recordId, isFavorite);

        if (updated > 0) {
            if (isFavorite == 1) {
                // 收藏操作
                dailyPracticesMapper.addToFavorites(userId, questionId);
            } else {
                // 取消收藏操作
                dailyPracticesMapper.removeFromFavorites(userId, questionId);
            }
            return true;
        }
        return false;
    }
}